let express = require("express");
let router = express.Router();
let QRCode = require('qr-image');



router.get("/codeImage", async (req, res, next) => {
    let url = 'https://www.baidu.com'

    // 二维码尺寸，输入时为了保证精确性，请确保为21的公倍数，否则按四舍五入处理.
    // 如果为空,默认为5,即尺寸为105*105
    let size = Math.round(req.query.size/21) || 5;

    // 白色外边距，输入时为了保证精确性，请确保为5的公倍数，否则按四舍五入处理.
    // 如果为空,默认为2,即尺寸为10
    let margin = Math.round(req.query.margin/10) || 2 ;

    let type = req.query.type;

    // 如果有type参数,返回base64
    if(type){
        let codeStr = QRCode.imageSync( url ,{ type: 'png',size:size, margin:margin});
        let base64='data:image/jpeg;base64,'+ codeStr.toString('base64');
        res.writeHead(200, {'Content-Type':'text/plain;charset=UTF-8'});
        res.end(base64);
        // 如果没有type参数,返回图片
    }else{
        let code = QRCode.image( url ,{ type: 'png',size:size, margin:margin});
        res.writeHead(200, {'Content-Type': 'image/png;charset=UTF-8'});
        code.pipe(res);
    }

});


module.exports = router;